package com.hongxun.project.assets.exportdetailed;

import com.github.pagehelper.util.StringUtil;
import com.hongxun.project.assets.exportdetailed.dxf.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by xiaoji on 2016/6/12.
 * dxf操作工具类
 */

public class DxfUtil {

/**
     * @param dataMap      word中需要展示的动态数据，用map集合来保存
     * @param templateName word模板名称，例如：test.ftl
     * @param filePath     文件生成的目标路径，例如：D:/wordFile/
     * @param fileName     生成的文件名称，例如：test.doc
     * @return 返回文件绝对路径
     * @Desc：生成dxf文件
     * @Date：2014-1-22下午05:33:42
     */

    @SuppressWarnings("unchecked")
    /*public static String createDxf(Map dataMap, String templateName, String filePath, String fileName) {
        try {
            //创建配置实例
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);

            //设置编码
            configuration.setDefaultEncoding("UTF-8");

            //ftl模板文件统一放至 com.designpass.cloud.template 包下面
            configuration.setClassForTemplateLoading(WordUtil.class, "/com/designpass/cloud/template/");

            //获取模板
            Template template = configuration.getTemplate(templateName);

            //输出文件
            File outFile = new File(filePath + File.separator + fileName);

            //如果输出目标文件夹不存在，则创建
            if (!outFile.getParentFile().exists()) {
                outFile.getParentFile().mkdirs();
            }

            //将模板和数据模型合并生成文件
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));

            //生成文件
            template.process(dataMap, out);

            //关闭流
            out.flush();
            out.close();
            return outFile.toPath().toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }*/


/**
     * svg内容转为dxf数据
     *
     * @param svgStr
     * @return
     */

    public static Map<String, Object> svgToDxfData(String svgStr) throws Exception {
        // 创建工厂
        DocumentBuilder docBuild = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = docBuild.parse(new ByteArrayInputStream(svgStr.getBytes("UTF-8")));

        //svg
        //创建多个图元
        Header header = new Header();
        Entities entities = new Entities();
        int k = Integer.parseInt(header.getLastId(), 16);
        //线
        NodeList nList = doc.getElementsByTagName("line");
        Element svgNode = doc.getDocumentElement();
        //设置图纸空间界限
        String svgWidth = svgNode.getAttribute("width");
        if (!StringUtil.isEmpty(svgWidth)) {
            header.setWidth(svgWidth);
        }
        String svgHeight = svgNode.getAttribute("height");
        if (!StringUtil.isEmpty(svgHeight)) {
            header.setHeight(svgHeight);
        }
        System.out.println("svgNode: " + svgNode.getAttribute("height"));
        for (int i = 0; i < nList.getLength(); i++) {
            Element node = (Element) nList.item(i);
            System.out.println("Name: " + node.getAttribute("x1"));
            Line line = new Line(node.getAttribute("x1"), CoordinateUtil.correctYCoord(node.getAttribute("y1"), header.getHeight()),
                    node.getAttribute("x2"), CoordinateUtil.correctYCoord(node.getAttribute("y2"), header.getHeight()));
            line.setStroke62(DxfColor.getIndexByRGB(node.getAttribute("stroke")) + "");
            line.setId(Integer.toHexString(k++).toUpperCase());
            //如果是虚线 那么久是虚线图层
            String styleStr = node.getAttribute("style");
            System.out.println("stroke-dasharray: " + styleStr.contains("stroke-dasharray"));
            if (styleStr.contains("stroke-dasharray")) {
                line.setLayer("虚线");
            }
            //线宽
            if (styleStr.contains("stroke-width: 3px")) {
                line.setLineWidth("200");
            } else if (styleStr.contains("stroke-width: 2px")) {
                line.setLineWidth("100");
            }
            entities.addLine(line);
        }
        //圆
        NodeList nList2 = doc.getElementsByTagName("circle");
        for (int i = 0; i < nList2.getLength(); i++) {
            Element node = (Element) nList2.item(i);
            System.out.println("Name: " + node.getAttribute("cx"));
            //圆
            String fill = node.getAttribute("fill");
            if ("none".equals(fill) || "RGB(255,255,255)".equals(DxfColor.changeRgb(fill))) {
                Circle circle = new Circle(node.getAttribute("cx"), CoordinateUtil.correctYCoord(node.getAttribute("cy"), header.getHeight()), node.getAttribute("r"));
                circle.setStroke62(DxfColor.getIndexByRGB(node.getAttribute("stroke")) + "");
                circle.setId(Integer.toHexString(k++));
                entities.addCircle(circle);
            } else {
                //圆填充
                Hatch hatch = new Hatch(node.getAttribute("cx"),
                        CoordinateUtil.correctYCoord(node.getAttribute("cy"), svgNode.getAttribute("height")),
                        node.getAttribute("r"));
                hatch.setId(Integer.toHexString(k++).toUpperCase());
                hatch.setStroke62(DxfColor.getIndexByRGB(node.getAttribute("stroke")) + "");
                entities.addHatch(hatch);
            }
        }
        //文字
        NodeList nList3 = doc.getElementsByTagName("text");
        for (int i = 0; i < nList3.getLength(); i++) {
            Element node = (Element) nList3.item(i);
            System.out.println("Name: " + node.getTextContent());
            Text text = new Text(node.getAttribute("x"), CoordinateUtil.correctYCoord(node.getAttribute("y"), svgNode.getAttribute("height")), node.getTextContent(), "10");
            text.setId(Integer.toHexString(k++).toUpperCase());
            text.setStroke62(DxfColor.getIndexByRGB(node.getAttribute("fill")) + "");
            String rotationAngle = node.getAttribute("transform");
            if (StringUtil.isNotEmpty(rotationAngle)) {
                text.setRotationAngle("90");
            }
            entities.addText(text);
        }
        //矩形
        NodeList nList4 = doc.getElementsByTagName("rect");
        for (int i = 0; i < nList4.getLength(); i++) {
            Element node = (Element) nList4.item(i);
            double width = Double.parseDouble(node.getAttribute("width"));
            double height = Double.parseDouble(node.getAttribute("height"));
            String x110 = node.getAttribute("x");
            String y120 = node.getAttribute("y");
            String x210 = Double.parseDouble(x110) + width + "";
            String y220 = y120;
            String x310 = Double.parseDouble(x110) + width + "";
            String y320 = Double.parseDouble(y120) + height + "";
            String x410 = x110 + "";
            String y420 = Double.parseDouble(y120) + height + "";
            String fill = node.getAttribute("fill");
            if ("none".equals(fill) || "RGB(255,255,255)".equals(DxfColor.changeRgb(fill))) {
                LwPolyline lwPolyline = new LwPolyline(x110,
                        CoordinateUtil.correctYCoord(y120, header.getHeight())
                        , x210, CoordinateUtil.correctYCoord(y220, header.getHeight()), x310,
                        CoordinateUtil.correctYCoord(y320, header.getHeight()), x410,
                        CoordinateUtil.correctYCoord(y420, header.getHeight()));
                lwPolyline.setId(Integer.toHexString(k++).toUpperCase());
                lwPolyline.setStroke62(DxfColor.getIndexByRGB(node.getAttribute("stroke")) + "");
                entities.addLwPolyline(lwPolyline);
            } else {
                PolylineHatch polylineHatch = new PolylineHatch(x110,
                        CoordinateUtil.correctYCoord(y120, header.getHeight())
                        , x210, CoordinateUtil.correctYCoord(y220, header.getHeight()), x310,
                        CoordinateUtil.correctYCoord(y320, header.getHeight()), x410,
                        CoordinateUtil.correctYCoord(y420, header.getHeight()));
                polylineHatch.setId(Integer.toHexString(k++).toUpperCase());
                polylineHatch.setStroke62(DxfColor.getIndexByRGB(node.getAttribute("stroke")) + "");
                entities.addPolylineHatch(polylineHatch);
            }
        }

        //曲线
        NodeList nList5 = doc.getElementsByTagName("path");
        for (int i = 0; i < nList5.getLength(); i++) {
            Element node = (Element) nList5.item(i);
            String d = node.getAttribute("d");
            if (d.contains("Q")) {//根据控制点话贝塞尔曲线
                System.out.println(d);
                String[] p1arr = d.substring(d.indexOf("M") + 1, d.indexOf("Q")).trim().split(" ");
                String[] p2arr = d.substring(d.indexOf("Q") + 1, d.indexOf(",")).trim().split(" ");
                String[] p3arr = d.substring(d.indexOf(",") + 1).trim().split(" ");
                Spline spline = new Spline(p1arr[0], CoordinateUtil.correctYCoord(p1arr[1], header.getHeight()),
                        p2arr[0], CoordinateUtil.correctYCoord(p2arr[1], header.getHeight()),
                        p3arr[0], CoordinateUtil.correctYCoord(p3arr[1], header.getHeight()));
                spline.setId(Integer.toHexString(k++).toUpperCase());
                entities.addSpline(spline);
            }
        }
        //三角形
        NodeList nList6 = doc.getElementsByTagName("polygon");
        for (int i = 0; i < nList6.getLength(); i++) {
            Element node = (Element) nList6.item(i);
            String points = node.getAttribute("points");
            if (StringUtil.isNotEmpty(points)) {//三角形哈哈
                TriangleHatch triangleHatch = new TriangleHatch(points, header.getHeight());
                triangleHatch.setId(Integer.toHexString(k++).toUpperCase());
                entities.addTriangleHatch(triangleHatch);
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("header", header);
        result.put("entities", entities);
        header.setLastId(Integer.toHexString(k++).toUpperCase());
        return result;
    }

}

